package cn.wanho.config.encoder;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;

import cn.wanho.dto.ExamUser;
import cn.wanho.mapper.ExamUserMapper;
import cn.wanho.util.PassEnDeUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * @author heyang
 * @date Create in 2022/8/6 16:21
 * 记得要在配置类中注入为@Bean
 */
public class MyCustomerPasswordEncoder implements PasswordEncoder {

    private final Log logger = LogFactory.getLog(getClass());

    //private static final String STR ="wanhowanho";

    @Resource
    HttpServletRequest request;

    @Resource
    ExamUserMapper examUserMapper;

    @Override
    public String encode(CharSequence rawPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        String username = request.getParameter("username");
        String salt = getSalt(username);
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String pass = rawPassword.toString();
        String digestHex = md5.digestHex(md5.digestHex(pass)+salt);
        return digestHex;
    }

    private String getSalt(String username) {
        //这里从数据库中拿盐
        ExamUser examUser = examUserMapper.selectUserByName(username);
        String salt = examUser.getSalt();
        if (salt != null) {
            return salt;
        }else{
            return null;
        }

    }

    /**
     * 输入密码对比
     * @param rawPassword the raw password to encode and match
     * @param encodedPassword the encoded password from storage to compare with
     * @return
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        System.out.println("rawPass::"+rawPassword);
        System.out.println("----matches---");
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        if (encodedPassword == null || encodedPassword.length() == 0) {
            this.logger.warn("Empty encoded password");
            return false;
        }

        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //String encodePass = encodedPassword.toString();
        //请从数据库总查看对应的sql中存入的密码字段赋值给rawPass
        //String rawPass = null;
        String username = request.getParameter("username");
        String salt = getSalt(username);
        String digestHex01  = PassEnDeUtil.encoder(rawPassword.toString(),salt);
        //= md5.digestHex(STR+md5.digestHex(rawPassword.toString())+salt);
        return digestHex01.equals(encodedPassword);
    }

}
